from django.db import models



class AppStatus(models.Model):
    STATUS_Init = 1
    STATUS_Uploaded = 2
    STATUS_Processed = 3
    STATUS_Failed = 4
    STATUS_CHOICES = (
        (STATUS_Init, 'Initialised'),
        (STATUS_Uploaded, 'Uploaded'),
        (STATUS_Processed, 'Processed'),
        (STATUS_Failed, 'Failed'),
    )

# Create your models here.
class App(models.Model):
    ## Uploaded apk filename 
    filename = models.CharField(max_length=200)
    ## SHA1 hash of uploaded file
    filehash = models.CharField(max_length=40)
    ## Processing status of the app
    status = models.IntegerField(choices = AppStatus.STATUS_CHOICES, default = AppStatus.STATUS_Init)
    
    def __unicode__(self):
        return self.filename
    
class Review(models.Model):
    ## App is in a one-many relationship with Review
    app = models.ForeignKey(App)
    ## When is this review created
    date = models.DateTimeField('Review date')
    ## Detailed comment text
    comment = models.TextField()
    ## Overall score given to this app
    score = models.IntegerField()

    def __unicode__(self):
        return unicode(self.app) + "_" + self.comment[:12]
    
    
base="023456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ"
def enc(int_val):
    radix = len(base)
    r = ""
    while int_val:
        r =  base[int_val % radix] + r
        int_val /= radix
    return r
def dec(str_val):
    r = 0
    radix = len(base)
    for i in range(len(str_val)):
        x = base.find(str_val[i])
        if x == -1:
            return -1
        r = r * radix + x 
    return r

#def transform(x):
#    L = x >> 28
#    R = x & 0xFFFFFFF
#    for sk in [0xF09ACB12] * 2:
#        print L, R
#        L0 = L
#        L = L ^ ( (R + sk) & 0xFFFFFFF)  
#        R = L0
#        print L, R
#    return R << 28 | L
def transform(x):
    L = x >> 28
    R = x & 0xFFFFFFF
    return R << 28 | L

def get_apkid(apk_record):
    # 32 bit table index plus 24 bit hash as MAC
    hash_id = int(apk_record.filehash[:6], 16)
    file_id = apk_record.id
    
    apkid = transform((hash_id << 32) | file_id) # 56 bit
    
    print hash_id, file_id, apkid
    
    return enc(apkid)

def lookup_apkid(apkid):
    v = transform(dec(apkid))
    if v == -1:
        return None
    file_id = v & 0xFFFFFFFF
    hash_id = v >> 32
    
    try:
        app = App.objects.get(id = file_id)
    except App.DoesNotExist:
        return None
    
    if int(app.filehash[:6], 16) == hash_id:
        return app
    else:
        return None

